package entities;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import com.example.dotatrivia.R;


import Adapters.DownloadImageTask;
import android.content.Context;
import android.content.res.Resources;
import android.widget.ImageView;



public class Hero extends ReadXMLFile{
	
	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getLocalized_name() {
		return localized_name;
	}
	
	public static final String xmlFileName = "Heroes.xml";
	
	public static final String urlXml = "http://api.steampowered.com/IEconDOTA2_205790/GetHeroes/v0001/?language=en&key=D3A46D85EE3EBF27D6F222F20922F903&format=xml";
	
	private static final int LIST_ID = 1;
	
	private static final int LIST_NAME = 0;
	
	private static final int LIST_LOCALIZED_NAME = 2;
		
	private int id;
	
	private String name;
	
	private String localized_name;
	
	private static List<Hero> heroes = null;
	
	public static int count = 108;
	
	private static final String baseUrl = "http://cdn.dota2.com/apps/dota2/images/heroes/";
	
	private static final String endUrl = "_lg";
	

	public static List<Hero> getHeroes() {
		return heroes;
	}

	private Hero(int id, String name, String localized_name){		
		this.id = id;
		this.name = name;
		this.localized_name = localized_name;		
	}
	
	protected void init(InputStream in) {
		tagName = "hero";
		branchName = "heroes";
		fieldNames = new String[]{"id", "name", "localized_name"};
		try {
			fillHeroes(in);
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public Hero(InputStream in){
		init(in);
	}
	
	public String getHeroImageUrl(int id){

		if(getById(id) != null){
		return baseUrl+getById(id).getName().replaceAll("npc_dota_hero_", "")+endUrl;
		}
		else return null;
		
	}
	
	private void fillHeroes( InputStream in) throws XmlPullParserException, IOException{
		if(heroes==null){
		@SuppressWarnings("unchecked")
		List<List<String>> list = parse(in);
		heroes = new ArrayList<Hero>();
		for(List<String> l: list){
			heroes.add(new Hero(Integer.valueOf(l.get(LIST_ID)), l.get(LIST_NAME), l.get(LIST_LOCALIZED_NAME)));
		}
		
		}
	}
	
	public Hero getById(int id) {
		Hero he = null;
		for(Hero h: heroes){
			if(h.getId()==id){
				he = h;
			}
				
		}
		return he;

	}

	public int getImgRes(Context c) {
	
		Resources r = c.getResources();		
		return 	r.getIdentifier(getName().replaceAll("npc_dota_hero_", "")+endUrl, "drawable", c.getPackageName());
	}
}
